//
//  StarTrendViewController.m
//  LiveStar
//
//  Created by 漪珊 on 2017/2/14.
//  Copyright © 2017年 apple. All rights reserved.
//

#import "StarTrendViewController.h"
#import "SendTrendViewController.h"
#import "FansTrendDetailViewController.h"
#import "StarLeavewordViewController.h"
#import "StarTrendTopView.h"
#import "FansTrdModel.h"
#import "FansTrdFrameModel.h"
#import "FanstrdNormalCell.h"
#import "SuperCommentCell.h"
#import "SuperCommentModel.h"

@interface StarTrendViewController ()<UITableViewDelegate,UITableViewDataSource,FanstrdNormalCellDelegate,UITextFieldDelegate,SuperCommentCellDelegate>{
    NSArray *_itemsArray;
    NSMutableArray *_buttonsArray;
    NSMutableArray *_trendDataArray;
    NSMutableArray *_dataFrameArray;
    NSMutableArray *_leavelistArray;
    UITextField *_msgInputFeild;
}
@property (nonatomic, strong) UIView *sliderline;
@property (nonatomic, strong) UIScrollView *scrollView;
@property (nonatomic, strong) UITableView *trendTableView;
@property (nonatomic, strong) UITableView *leaveWordTabelView;
@property (nonatomic, strong) UITableView *privateLetterTableView;
@property (nonatomic, strong) StarTrendTopView *topView;

@property (nonatomic, strong) UIView *msgInputView;
@property (nonatomic, assign) CGFloat history_Y_offset;//记录table的offset.y
@property (nonatomic, assign) CGFloat seletedCellHeight;//记录点击cell的高度，高度由代理传过来
@property (nonatomic, assign) BOOL isShowKeyBoard;//记录点击cell的高度，高度由代理传过来
@property (nonatomic, assign) BOOL needUpdateOffset;//控制是否刷新table的offset
@property (nonatomic,copy)NSIndexPath *currentIndexPath;
@property (nonatomic, strong) CommentModel *replayTheSeletedCellModel;//专门用来回复选中的cell的model
@property (nonatomic, copy) NSString *parentId;
@property (nonatomic, copy) NSString *parentudid;
@property (nonatomic, copy) NSString *replyname;
@end

@implementation StarTrendViewController

- (UIView *)msgInputView {
    if (!_msgInputView) {
        //输入框
        _msgInputView = [[UIView alloc] initWithFrame:CGRectMake(0, kSCREEN_HEIGHT -kNAV_HEIGHT-kTABBAE_HEIGHT, kSCREEN_WIDTH, 50 )];
        _msgInputView.backgroundColor = [UIColor whiteColor];
        UIView *sepline = [[UIView alloc] init];
        [_msgInputView addSubview:sepline];
        sepline.frame = CGRectMake(0, 0, kSCREEN_WIDTH, 0.5);
        sepline.backgroundColor = [UIColor cellLineColor];
        UIButton *sendBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        sendBtn.frame = CGRectMake(self.view.width - 15 - 50, 0, 50, 50);
        [sendBtn setTitle:@"发送" forState:UIControlStateNormal];
        [sendBtn.titleLabel setFont:[UIFont systemFontOfSize:16]];
        [sendBtn setTitleColor:UIColorFromRGB(0x0ACCAC) forState:UIControlStateNormal];
        [sendBtn setBackgroundColor:[UIColor clearColor]];
        [sendBtn addTarget:self action:@selector(clickSend:) forControlEvents:UIControlEventTouchUpInside];
        
        _msgInputFeild = [[UITextField alloc] initWithFrame:CGRectMake(10,7.5,sendBtn.left - 20,30)];
        _msgInputFeild.backgroundColor = [UIColor clearColor];
        _msgInputFeild.returnKeyType = UIReturnKeySend;
        _msgInputFeild.borderStyle = UITextBorderStyleRoundedRect;
        _msgInputFeild.placeholder = @"留下你想对明星说的话...";
        _msgInputFeild.delegate = self;
        _msgInputFeild.textColor = [UIColor blackColor];
        _msgInputFeild.font = [UIFont systemFontOfSize:14];
        
        [_msgInputView addSubview:_msgInputFeild];
        [_msgInputView addSubview:sendBtn];
        
    }
    [_msgInputFeild becomeFirstResponder];
    return _msgInputView;
}

//监听键盘高度变化
-(void)keyboardFrameDidChange:(NSNotification*)notice
{
    NSDictionary * userInfo = notice.userInfo;
    NSValue * endFrameValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect endFrame = endFrameValue.CGRectValue;
    [UIView animateWithDuration:0.25 animations:^{
        _msgInputView.y = endFrame.origin.y - _msgInputView.height - kNAV_HEIGHT-kTABBAE_HEIGHT;
        if (_msgInputView.y == kSCREEN_HEIGHT-kNAV_HEIGHT-kTABBAE_HEIGHT-50) {
            self.parentId = @"";
            self.parentudid = @"";
            _msgInputFeild.placeholder = @"留下你想对明星说的话...";
        }
    }];
}

#pragma mark -- 留言列表
- (void)LeaveListRequest {
    NSDictionary *dict = @{@"udid":User_ID,
                           @"token":TOKEN,
                           @"cid":User_ID,
                           @"type":@"30", //留言列表
                           @"page":@"1"
                           };
    NSString *urlString = [TEST_URL stringByAppendingString:KSCommentList];
    [NetworkTools postReqeustWithParams:dict UrlString:urlString successBlock:^(id responseObject) {
        if ([responseObject[@"code"] intValue] == 200) {
            if (_leavelistArray.count > 0) {
                [_leavelistArray removeAllObjects];
            }
            NSArray *array = responseObject[@"data"][@"list"];
            for (NSDictionary *commentDict in array) {
                SuperCommentModel *model1 = [[SuperCommentModel alloc] initWithDict:commentDict];
                NSArray *commentArr = model1.children;
                model1.commentArray = [NSMutableArray arrayWithCapacity:1];
                for (NSDictionary *cidict in commentArr) {
                    CommentModel *model = [[CommentModel alloc] initWithDict:cidict];
                    [model1.commentArray addObject:model];
                }
                [_leavelistArray addObject:model1];
            }
            [self.leaveWordTabelView reloadData];
        }
    } failureBlock:^(NSError *error) {
        
    } showHUD:NO];
}

#pragma mark -- 点赞 cid:帖子id
- (void)praiseClickRequestWithCid:(NSString *)cid IndexPath:(NSIndexPath *)indexPath {
    NSDictionary *dict = @{@"udid":User_ID,
                           @"token":TOKEN,
                           @"cid":cid
                           };
    NSString *urlString = [TEST_URL stringByAppendingString:kTrendLike];
    [NetworkTools postReqeustWithParams:dict UrlString:urlString successBlock:^(id responseObject) {
        if ([responseObject[@"code"] intValue] == 200) {
            FansTrdFrameModel *frameModel = _dataFrameArray[indexPath.row];
            NSString *status = responseObject[@"data"][@"status"];
            frameModel.trendModel.booked = status;
            if ([status intValue] == 10) {//点赞成功
                frameModel.trendModel.c_like = [NSString stringWithFormat:@"%d",[frameModel.trendModel.c_like intValue] + 1];
            } else {//取消点赞
                 frameModel.trendModel.c_like = [NSString stringWithFormat:@"%d",[frameModel.trendModel.c_like intValue] - 1];
            }
            [self.trendTableView reloadData];
        }
    } failureBlock:^(NSError *error) {
        
    } showHUD:NO];
}

#pragma mark -- 留言回复request
//发送留言 type:@"30"
- (void)SendLeaveWordRequestWithContent:(NSString *)content Parent:(NSString *)parent Pudid:(NSString *)pudid {
    NSDictionary *dict = @{@"udid":User_ID,
                           @"token":TOKEN,
                           //                           @"cid":self.s_uid,
                           @"description":content,
                           @"type":@"30",
                           @"parent":parent,
                           @"pudid":pudid
                           };
    NSString *urlString = [TEST_URL stringByAppendingString:kSendComment];
    [self showHUDInView:self.view title:nil];
    [NetworkTools postReqeustWithParams:dict UrlString:urlString successBlock:^(id responseObject) {
        [_msgInputFeild resignFirstResponder];
        [self hideHUD];
        if ([responseObject[@"code"] intValue] == 200) {
            _msgInputFeild.text = nil;
            _msgInputFeild.placeholder = @"留下你想对明星说的话...";
            [self showTitle:responseObject[@"data"][@"message"]];
            NSDictionary *newData = responseObject[@"data"][@"comment"];
            [self updateReplylistWithData:newData];
        }
    } failureBlock:^(NSError *error) {
        [_msgInputFeild resignFirstResponder];
        [self hideHUD];
    } showHUD:NO];
}
//更新留言子回复列表
- (void)updateReplylistWithData:(NSDictionary *)dataDict {
    CommentModel *model = [[CommentModel alloc] init];
    model.c_udid = dataDict[@"c_uid"];
    //    model.cid = self.s_uid;
    model.c_content = dataDict[@"c_content"];
    model.c_createtime = dataDict[@"c_createtime"];
    model.cnickname = dataDict[@"u_nickname"];
    model.pnickname = self.replyname;
    model.c_parent = dataDict[@"c_parent"];
    model.c_parudid = dataDict[@"c_parudid"];
    SuperCommentModel *superModel = [_leavelistArray objectAtIndex:self.currentIndexPath.row];
    superModel.shouldUpdateCache = YES;
    [superModel.commentArray addObject:model];
    superModel.shouldUpdateCache = YES;
    [self reloadCellHeightForModel:superModel atIndexPath:self.currentIndexPath];
}

- (void)reloadCellHeightForModel:(SuperCommentModel *)model atIndexPath:(NSIndexPath *)indexPath{
    model.shouldUpdateCache = YES;
    [self.leaveWordTabelView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
}


#pragma mark --  动态列表发送请求
- (void)FTrendListRequest {
    NSDictionary *dict = @{
                           @"udid":User_ID,
                           @"token":TOKEN,
                           @"page":@"1"
                           };
    NSString *urlString = [TEST_URL stringByAppendingString:kStarTrendList];
    [NetworkTools postReqeustWithParams:dict UrlString:urlString successBlock:^(id responseObject) {
        if ([responseObject[@"code"] intValue] == 200) {
            NSArray *array = responseObject[@"data"][@"list"];
            if (_dataFrameArray.count > 0) {
                [_dataFrameArray removeAllObjects];
            }
            if (_trendDataArray.count > 0) {
                [_trendDataArray removeAllObjects];
            }
            for (NSDictionary *trendDict in array) {
                FansTrdModel *model = [[FansTrdModel alloc] initWithDict:trendDict];
                NSArray *imageArray = [model.c_images componentsSeparatedByString:@","];
                model.pictureArray = [NSMutableArray arrayWithArray:imageArray];
                [_trendDataArray addObject:model];
                FansTrdFrameModel *frameModel = [[FansTrdFrameModel alloc] init];
                frameModel.trendModel = model;
                [_dataFrameArray addObject:frameModel];
            }
            [self.trendTableView reloadData];
        }
    } failureBlock:^(NSError *error) {
        
    } showHUD:NO];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setUpUI];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardFrameDidChange:) name:UIKeyboardWillChangeFrameNotification object:nil];
    [self setNav];
    [self SliderAction:_buttonsArray[0]];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(ReloadData:) name:kStarRoomTrendListNotifica object:nil];
}

- (void)ReloadData:(NSNotification *)notifica {
    [self SliderAction:_buttonsArray[0]];
}
- (void)setUpUI {
    _itemsArray = @[@"动态",@"留言"];
    
    _buttonsArray = [NSMutableArray arrayWithCapacity:1];
    _dataFrameArray = [NSMutableArray arrayWithCapacity:1];
    _trendDataArray = [NSMutableArray arrayWithCapacity:1];
    _leavelistArray = [NSMutableArray arrayWithCapacity:1];
    [self creatScrollview];
    
}
- (void)setNav {
    self.navigationItem.titleView = [self creatSliderViewWithItmes:(int)_itemsArray.count];
}
- (void)creatScrollview {
    self.scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, kSCREEN_WIDTH, kSCREEN_HEIGHT - kTABBAE_HEIGHT - kNAV_HEIGHT)];
    self.scrollView.delegate = self;
    self.scrollView.pagingEnabled = YES;
    self.scrollView.bounces = NO;
    self.scrollView.scrollEnabled = YES;
    self.scrollView.showsHorizontalScrollIndicator = NO;
    self.scrollView.showsVerticalScrollIndicator = NO;
    self.scrollView.alwaysBounceVertical = NO;
    self.scrollView.contentSize = CGSizeMake(kSCREEN_WIDTH *_itemsArray.count, kSCREEN_HEIGHT - kTABBAE_HEIGHT - kNAV_HEIGHT);
    [self.view addSubview:self.scrollView];
    self.trendTableView = [[UITableView alloc] init];
    self.trendTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kSCREEN_WIDTH, kSCREEN_HEIGHT- kTABBAE_HEIGHT - kNAV_HEIGHT)];
    
    self.trendTableView.delegate = self;
    self.trendTableView.dataSource = self;
    self.trendTableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
    self.trendTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.trendTableView.backgroundColor = [UIColor whiteColor];
    self.topView = [[NSBundle mainBundle] loadNibNamed:@"StarTrendTopView" owner:self options:nil].lastObject;
    self.trendTableView.tableHeaderView = self.topView;
    __weak typeof(self) weakSelf = self;
    self.topView.SendTrend = ^(){
        SendTrendViewController *trendVC = [[SendTrendViewController alloc] init];
        [weakSelf.navigationController pushViewController:trendVC animated:YES];
    };
    [self.scrollView addSubview:self.trendTableView];
    
    self.leaveWordTabelView = [[UITableView alloc] init];
    self.leaveWordTabelView = [[UITableView alloc] initWithFrame:CGRectMake(kSCREEN_WIDTH, 0, kSCREEN_WIDTH, kSCREEN_HEIGHT-kNAV_HEIGHT-kTABBAE_HEIGHT)];
    self.leaveWordTabelView.delegate = self;
    self.leaveWordTabelView.dataSource = self;
    self.leaveWordTabelView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.leaveWordTabelView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
    self.leaveWordTabelView.backgroundColor = [UIColor whiteColor];
    [self.leaveWordTabelView registerClass:[SuperCommentCell class] forCellReuseIdentifier:@"superCommentCellID"];
    [self.scrollView addSubview:self.leaveWordTabelView];
    [self.scrollView addSubview:_msgInputView];
}

- (UIView *)creatSliderViewWithItmes:(int)count {
    UIView *sliderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 160, 42)];
    CGFloat Width = sliderView.width/count;
    for (int i = 0; i<count; i++) {
        UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(Width*i, 0, Width, 40)];
        btn.titleLabel.font = UIFont(18);
        [btn setTitle:_itemsArray[i] forState:UIControlStateNormal];
        [btn addTarget:self action:@selector(SliderAction:) forControlEvents:UIControlEventTouchUpInside];
        [sliderView addSubview:btn];
        [_buttonsArray addObject:btn];
    }
    
    self.sliderline = [[UIView alloc] initWithFrame:CGRectMake(0, 40, Width, 2)];
    self.sliderline.backgroundColor = [UIColor colorWithHexString:@"04DD98"];
    [sliderView addSubview:self.sliderline];
    return sliderView;
}

//SliderAction
- (void)SliderAction:(UIButton *)sender {
    [UIView animateWithDuration:0.3 animations:^{
        self.sliderline.centerX = sender.centerX;
        [self.sliderline layoutIfNeeded];
    }];
    if (sender == _buttonsArray[0]) {//动态
        [self FTrendListRequest];
        [self.scrollView setContentOffset:CGPointMake(0, 0) animated:NO];
    } else if (sender == _buttonsArray[1]) {//留言
        [self LeaveListRequest];
        [self.scrollView setContentOffset:CGPointMake(kSCREEN_WIDTH, 0) animated:NO];
    }
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (tableView == self.trendTableView) {
        return _dataFrameArray.count;
    } else if (tableView == self.leaveWordTabelView) {
        return _leavelistArray.count;
    }
    return 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (tableView == self.trendTableView) {
        FanstrdNormalCell *cell = [FanstrdNormalCell loadNormalCellWithTabelView:tableView];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.delegate = self;
        FansTrdFrameModel *model = _dataFrameArray[indexPath.row];
        cell.frameModel = model;
        cell.delegate = self;
        return cell;

    }
    SuperCommentCell *cell = [tableView dequeueReusableCellWithIdentifier:@"superCommentCellID"];
    cell.delegate = self;
    __weak __typeof(self) weakSelf= self;
    __block SuperCommentModel *model = [_leavelistArray objectAtIndex:indexPath.row];
    [cell configCellWithModel:model indexPath:indexPath];
    //点击文字
    cell.TapTextBlock=^(UILabel *desLabel){
        [_msgInputFeild becomeFirstResponder];
        self.replyname = model.u_nickname;
        weakSelf.parentId = model.cid;
        weakSelf.parentudid = model.c_udid;
        weakSelf.currentIndexPath = indexPath;
    };
    cell.TapReplyBlock =  cell.TapReplyBlock = ^(UIButton *replyBtn){
        [_msgInputFeild becomeFirstResponder];
        _msgInputFeild.placeholder = [NSString stringWithFormat:@"回复:@%@",model.u_nickname];
        self.replyname = model.u_nickname;
        weakSelf.parentId = model.cid;
        weakSelf.parentudid = model.c_udid;
        weakSelf.currentIndexPath = indexPath;
    };
    return cell;

}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (tableView == self.trendTableView) {
        FansTrendDetailViewController *detailVC = [FansTrendDetailViewController new];
        FansTrdFrameModel *model = _dataFrameArray[indexPath.row];
        detailVC.trendFrameModel = model;
        [self.navigationController pushViewController:detailVC animated:YES];
    }

}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (tableView == self.trendTableView) {
        FansTrdFrameModel *model = _dataFrameArray[indexPath.row];
        return model.cellHeight;
    } else if (tableView == self.leaveWordTabelView) {
        SuperCommentModel *model = [_leavelistArray objectAtIndex:indexPath.row];
        CGFloat h = [SuperCommentCell hyb_heightForTableView:tableView config:^(UITableViewCell *sourceCell) {
            SuperCommentCell *cell = (SuperCommentCell *)sourceCell;
            [cell configCellWithModel:model indexPath:indexPath];
        } cache:^NSDictionary *{
            NSDictionary *cache = @{kHYBCacheUniqueKey : model.cid,
                                    kHYBCacheStateKey  : @"",
                                    kHYBRecalculateForStateKey : @(model.shouldUpdateCache)};
            model.shouldUpdateCache = NO;
            return cache;
        }];
        return h;
    }
    return 0;
}
#pragma mark -- 发送留言
- (void)clickSend:(UIButton *)sender {
    if (_msgInputFeild.text.length) {
        [self SendLeaveWordRequestWithContent:_msgInputFeild.text Parent:self.parentId Pudid:self.parentudid];
    } else {
        [self showTitle:@"请您输入留言内容"];
    }
}

#pragma mark -- FanstrdNormalCellDelegate(点赞,评论,分享)
- (void)praiseClickwithCell:(FanstrdNormalCell *)trendcell Tag:(int)actionTag {
    NSIndexPath *indexPath = [self.trendTableView indexPathForCell:trendcell];
    FansTrdFrameModel *frameModel = _dataFrameArray[indexPath.row];
    switch (actionTag) {
        case 0:{//点赞
            [self praiseClickRequestWithCid:frameModel.trendModel.cid IndexPath:indexPath];
        }
            break;
        case 1:{//评论
            FansTrendDetailViewController *detailVC = [FansTrendDetailViewController new];
            FansTrdFrameModel *model = _dataFrameArray[indexPath.row];
            detailVC.trendFrameModel = model;
            [self.navigationController pushViewController:detailVC animated:YES];
        }
            break;
        case 2:{//分享
            FansTrendDetailViewController *detailVC = [FansTrendDetailViewController new];
            FansTrdFrameModel *model = _dataFrameArray[indexPath.row];
            detailVC.trendFrameModel = model;
            [self.navigationController pushViewController:detailVC animated:YES];
        }
            break;
            
        default:
            break;
    }
}
#pragma mark -- SuperCommentCellDelegate
-  (void)passCellHeight:(CGFloat )cellHeight commentModel:(CommentModel *)commentModel   commentCell:(CommentCell *)commentCell SuperCommentCell:(SuperCommentCell *)superCommentCell {
    self.replyname = commentModel.cnickname;
    self.needUpdateOffset = YES;
    self.replayTheSeletedCellModel = commentModel;
    self.currentIndexPath = [self.leaveWordTabelView indexPathForCell:superCommentCell];
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    self.history_Y_offset = [commentCell.contentLabel convertRect:commentCell.contentLabel.bounds toView:window].origin.y;
    self.seletedCellHeight = cellHeight;
}

#pragma mark -- UITextFieldDelegate
- (void)textFieldDidBeginEditing:(UITextField *)textField {
}

- (void)textFieldDidEndEditing:(UITextField *)textField {
    
}


-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [_msgInputFeild resignFirstResponder];
    if (_msgInputFeild.text.length) {
        [self SendLeaveWordRequestWithContent:_msgInputFeild.text Parent:self.parentId Pudid:self.parentudid];
    } else {
        [self showTitle:@"请您输入留言内容"];
    }
    return YES;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
